import React from 'react';
import { Link } from 'react-router';
import { Button, Row, Col, message, Modal, Input, Select, Form } from 'antd';
import moment from 'moment';
import $ from 'jquery';
import Config from '../../common/config';
import Region from '../../common/region';

const Option = Select.Option;
const FormItem = Form.Item;
const config = new Config;
const token = sessionStorage.getItem('token');

class applyOperation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userId: JSON.parse(sessionStorage.getItem('UserInfo')).userid, // 用户ID
      orderId: this.props.params.orderId,
      data: {}, // 订单数据
      product: {}, // 退款商品
      refundVisible: false, // 退款模态框显示
      refundWay: [], // 退款途径
      operationValue: '1', // 操作值
      valetReason: '', // 代客理由
      detailedDescription: '', // 详细说明
      typeValue: '', // 退款方式
    }
    this.hiddenRefund = this.hiddenRefund.bind(this);
    this.checkRefundMoney = this.checkRefundMoney.bind(this);
    this.refund = this.refund.bind(this);
    this.selectOperation = this.selectOperation.bind(this);
    this.selectReason = this.selectReason.bind(this);
    this.inputDetail = this.inputDetail.bind(this);
    this.valetOperation = this.valetOperation.bind(this);
    this.selectType = this.selectType.bind(this);
  }

  componentWillMount() {
    this.getData();

    // 获取退款方式
    $.ajax({
      url: `${config.JuseOrder}/orderList/getRefundWay`,
      type: 'get',
      headers: {
        'Authorization': 'Bearer ' + token,
      },
      data: {
        orderId: this.state.orderId
      },
      success: (data) => {
        console.log('退款途径', data);
        if (data.code === 200) {
          this.setState({
            refundWay: data.data,
          });
        }
      }
    });
  }

  // 获取订单详情内容
  getData() {
    $.ajax({
      url: `${config.JuseOrder}/orderList/detail`,
      type: 'get',
      headers: {
        'Authorization': 'Bearer ' + token,
      },
      data: {
        orderId: this.state.orderId
      },
      success: (res) => {
        console.log('订单数据', res);
        if (res.code === 200) {
          this.setState({
            data: res.data,
          });
        }
      }
    });
  }

  // 显示退款按钮
  showRefundStatus(product) {
    const order = this.state.data;
    if (!order) {
      return;
    }
    let text;
    if (order.isAlreadyPay) {
      switch (product.refundStatus) {
        case 0:
          text = <a href='javascript:void(0)' onClick={this.showRefund.bind(this, product)}>退款</a>;
          break;
        case 1:
          text = '退款审核中';
          break;
        case 2:
          text = '退款成功';
          break;
      }
    }
    return text;
  }

  // 显示退款模态框
  showRefund(product) {
    this.setState({
      refundVisible: true,
      product
    });
    this.props.form.resetFields();
    let value;
    // if (this.state.data.paymentMethod === '货到付款') {
    value = 'other';
    // } else {
    // value = 'return';
    // }
    this.props.form.setFieldsValue({
      refundType: value
    });
    this.setState({
      typeValue: value
    });
  }

  // 隐藏退款模态框
  hiddenRefund() {
    this.setState({
      refundVisible: false,
    });
  }

  // 检查退款金额
  checkRefundMoney(rule, value, callback) {
    const productDetail = this.state.product;
    if (productDetail.number && productDetail.paidPrice) {
      if (Number(value) !== Number(value)) {
        return callback('请输入数字');
      }
      const money = productDetail.number * productDetail.paidPrice;
      if (value > money) {
        return callback('退款金额不能大于购买金额');
      }
    }
    callback();
  }

  // 退款
  refund(e) {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      console.log(values);
      if (!err) {
        const data = {
          orderId: this.state.orderId,
          productId: this.state.product.productId,
          refundType: values.refundType,
          refundMoney: values.refundMoney,
          refundReason: values.refundReason
        };
        if (values.refundType === 'other') {
          data.refundWay = values.refundWay;
          data.refundAccountNumber = values.refundAccountNumber;
          data.refundUserName = values.refundUserName;
        }
        $.ajax({
          url: `${config.JuseOrder}/orderList/applyForRefund`,
          type: 'post',
          headers: {
            'Authorization': 'Bearer ' + token,
          },
          data,
          success: (data) => {
            console.log('退款', data);
            if (data.code === 200) {
              this.setState({
                refundVisible: false,
              }, () => {
                this.getData();
              });
            } else {
              message.error('不能退款');
            }
          }
        });
      }
    });
  }

  // 选择代客理由
  selectReason(value) {
    this.setState({
      valetReason: value
    });
  }

  // 选择操作
  selectOperation(value) {
    this.setState({
      operationValue: value
    });
  }

  // 输入详细说明
  inputDetail(e) {
    this.setState({
      detailedDescription: e.target.value
    });
  }

  // 代客操作
  valetOperation() {
    const { operationValue, valetReason: refundReason, detailedDescription } = this.state;
    switch (operationValue) {
      case '1':
        $.ajax({
          url: `${config.JuseOrder}/orderList/valetCancelOrder`,
          type: 'post',
          headers: {
            'Authorization': 'Bearer ' + token,
          },
          data: {
            orderId: this.state.orderId,
            refundReason,
            detailedDescription,
            handlePerson: this.state.userId
          },
          success: (data) => {
            console.log('代客取消订单', data);
            message.config({ top: 160 });
            if (data.code === 200) {
              message.success('代客取消订单成功');
            } else {
              message.error('不能取消此订单');
            }
          }
        });
        break;
      case '2':
        $.ajax({
          url: `${config.JuseOrder}/orderList/valetRejection`,
          type: 'post',
          headers: {
            'Authorization': 'Bearer ' + token,
          },
          data: {
            orderId: this.state.orderId,
            refundReason,
            detailedDescription,
            handlePerson: this.state.userId
          },
          success: (data) => {
            console.log('代客拒收', data);
            message.config({ top: 160 });
            if (data.code === 200) {
              message.success('代客拒收成功');
            } else {
              message.error('不能代客拒收');
            }
          }
        });
        break;
    }
  }

  // 选择退款方式
  selectType(value) {
    this.setState({
      typeValue: value
    });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 16 } };
    return (
      <div className='contentBox clearfix'>
        <div style={{ marginBottom: 15, padding: 10 }}>
          <Link className='onlicksty' to={'/orderDetail/' + this.state.data.orderId}>&lt; 返回</Link>
        </div>
        <div className='ppp-a'>
          <Row>
            <Col>代客申请操作</Col>
          </Row>
        </div>
        <Row>
          <Col span={4}>
            <span style={{ marginRight: 10 }}>订单编号：</span>
            <span>{this.state.data.orderId}</span>
          </Col>
        </Row>
        <div>
          <ul className='detaiList detaiList-adc'>
            <li>
              <Col span={4}>商品图片</Col>
              <Col span={4}>商品内码</Col>
              <Col span={4}>商品单价</Col>
              <Col span={4}>商品数量</Col>
              <Col span={4}>小记</Col>
              <Col span={4}>操作</Col>
            </li>
            {
              this.state.data.productList && this.state.data.productList.map((item, i) => (
                <li key={i}>
                  <Col span={4}><img src={item.imageUrl + item.listImage} style={{ width: 50, height: 50 }} /></Col>
                  <Col span={4}>{item.productId}</Col>
                  <Col span={4}>{item.marketPrice}</Col>
                  <Col span={4}>{item.number}</Col>
                  <Col span={4}>{(item.marketPrice * item.number).toFixed(2)}</Col>
                  <Col span={4}>{this.showRefundStatus(item)}</Col>
                </li>
              ))
            }
          </ul>
        </div>
        {
          !this.state.data.isAlreadyPay
            ?
            <div>
              <div className='out-asd-too'>操作</div>
              <div className='asdsf-ss'>
                <Row>
                  <Col span={6}>
                    <span style={{ marginLeft: 20 }}>服务类型：</span>
                    <Select value={this.state.operationValue} onChange={this.selectOperation} style={{ width: 200 }}>
                      <Option value='1'>代客取消订单</Option>
                      <Option value='2'>代客拒收</Option>
                    </Select>
                  </Col>
                  <Col span={6}>
                    <span>申请理由：</span>
                    <Select onChange={this.selectReason} style={{ width: 200 }}>
                      <Option value='下错单了'>下错单了</Option>
                    </Select>
                  </Col>
                </Row>
              </div>
              <div className='asdsf-ss'>
                <Row>
                  <Col>
                    <span style={{ marginLeft: 20, float: 'left' }}>详细说明：</span>
                    <Input type='textarea' onChange={this.inputDetail} style={{ width: '50%', minHeight: 150 }} />
                  </Col>
                </Row>
              </div>
              <div className='asdsf-ss'>
                <Row>
                  <Col offset={6} span={18}>
                    <Button type='primary' onClick={this.valetOperation} style={{ width: 100, height: 30 }}>提交</Button>
                  </Col>
                </Row>
              </div>
            </div>
            :
            ''
        }
        <Modal
          visible={this.state.refundVisible}
          footer={null}
          closable={false}
        >
          <Form onSubmit={this.refund}>
            <FormItem {...formItemLayout} label='退款商品：'>
              <div>
                <img src={this.state.product.imageUrl + this.state.product.listImage} style={{ width: 50, height: 50 }} />
                <span>{this.state.product.productName}</span>
              </div>
            </FormItem>
            <FormItem {...formItemLayout} label='退款方式：'>
              {getFieldDecorator('refundType', {
              })(
                <Select onChange={this.selectType}>
                  {/* {
                    this.state.data.paymentMethod === '货到付款'
                      ?
                      ''
                      :
                      <Option value='return'>原路返回</Option>
                  } */}
                  <Option value='other'>其他途径</Option>
                </Select>
              )}
            </FormItem>
            {
              this.state.typeValue === 'other'
                ?
                <FormItem {...formItemLayout} label='退款方式：'>
                  {getFieldDecorator('refundWay', {
                    rules: [{ required: true, message: '请选择退款途径' }],
                  })(
                    <Select>
                      {
                        this.state.refundWay.map((item, index) => {
                          return (
                            <Option key={index} value={item.refundWay}>
                              {item.refundWay}
                            </Option>
                          )
                        })
                      }
                    </Select>
                  )}
                </FormItem>
                :
                ''
            }
            {
              this.state.typeValue === 'other'
                ?
                <FormItem {...formItemLayout} label='退款账号：'>
                  {getFieldDecorator('refundAccountNumber', {
                    rules: [{ required: true, message: '请选择退款账号' }],
                  })(
                    <Input />
                  )}
                </FormItem>
                :
                ''
            }
            {
              this.state.typeValue === 'other'
                ?
                <FormItem {...formItemLayout} label='账户号：'>
                  {getFieldDecorator('refundUserName', {
                    rules: [{ required: true, message: '请选择账户号' }],
                  })(
                    <Input />
                  )}
                </FormItem>
                :
                ''
            }
            <FormItem {...formItemLayout} label='退款金额：'>
              {getFieldDecorator('refundMoney', {
                rules: [{
                  required: true, message: '请选择退款金额'
                }, {
                  validator: this.checkRefundMoney,
                }],
              })(
                <Input placeholder='小于等于商品金额' />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label='退款原因：'>
              {getFieldDecorator('refundReason', {
                rules: [{ required: true, message: '请选择退款原因' }],
              })(
                <Input type='textarea' />
              )}
            </FormItem>
            <Row>
              <Col span={5} offset={5}>
                <Button htmlType='submit'>确定</Button>
              </Col>
              <Col span={5} offset={4}>
                <Button onClick={this.hiddenRefund}>取消</Button>
              </Col>
            </Row>
          </Form>
        </Modal>
      </div>
    )
  }
}

export default Form.create()(applyOperation);
